<template>
  <view class="share-box">
    <view v-if="isExpired" class="error-msg expired">
      该链接已过期
    </view>
    <view v-if="isUsed" class="error-msg used">
      无效的链接
    </view>
    <view v-if="isShowInfo" class="info-box">
      <view class="user-box">
        <i v-if="!shareUserIcon" class="user-icon iconfont icon-userCenter" />
        <image v-else class="user-icon" :src="shareUserIcon" mode="aspectFill"></image>
        <view class="user-info">{{ shareUserName }}邀请你加入项目</view>
      </view>
      <view class="project-box">
        <view class="project-name">{{ projectName }}</view>
      </view>
      <view class="btn-box">
<!--        <button v-if="isNewUser" class="btn-item accept" open-type="getPhoneNumber" @getphonenumber="getPhone">确定</button>-->
        <button class="btn-item accept" @click="accept()">确定</button>
        <button class="btn-item reject" @click="reject()">拒绝</button>
      </view>
    </view>
  </view>
</template>

<script>
  import { getImagePath } from '@/utils/index.js'
  export default {
    data() {
      return {
        isLoading: true,
        isExpired: false,
        isUsed: false,
        isNewUser: false,
        hasUserName: false,
        shareTicket: '',
        shareKey: '',
        shareUserIcon: '',
        shareUserName: '未知用户',
        userId: '',
        projectName: '未知项目',
        projectId: '',
        permissions: '',
      }
    },
    computed: {
      isShowInfo() {
        return !this.isLoading && !this.isExpired && !this.isUsed
      }
    },
    onLoad(query) {
      console.log('query:', query)
      this.shareKey = query.key
      uni.showLoading()
      this.getShareInfo()
    },
    methods: {
      checkUsed() {
        const app = getApp()
        const self = this
        wx.authPrivateMessage({
          shareTicket: app.globalData?.shareTicket,
          success(res) {
            console.log('authPrivateMessage success', res)
            self.getShareInfo()
          },
          fail(res) {
            console.log('authPrivateMessage fail', res)
            uni.hideLoading()
            self.isLoading = false
            self.isUsed = true
          }
        })
      },
      getShareInfo() {
        const self = this
        uni.request({
          url: '/project/share_info',
          method: 'GET',
          data: {
            key: self.shareKey
          },
          success(result) {
            if (result.data.success && result.data.data) {
              const { name = '未知用户', photo, xm_id, xm_name = '未知项目', permission } = result.data.data
              self.shareUserName = name;
              self.shareUserIcon = getImagePath(photo);
              self.projectName = xm_name;
              self.projectId = xm_id;
              self.permissions = permission;
              const app = getApp()
              app.globalData.targetProjectId = self.projectId
              self.login()
            } else {
              self.isExpired = true
            }
          },
          fail(res) {
            uni.hideLoading()
            self.isLoading = false
            self.isExpired = true
          }
        })
      },
      login() {
        const self = this
        uni.login({
          success (res) {
            if (res.code) {
              //发起网络请求
              uni.request({
                url: '/sys/login',
                method: 'POST',
                data: {
                  code: res.code
                },
                success(result) {
                  uni.hideLoading()
                  self.isLoading = false
                  if (result.data.success && result.data.data) {
                    const { id, name,  last_login } = result.data.data
                    self.userId = id
                    self.isNewUser = !name
                    self.hasUserName = !!name
                  }
                }
              })
            } else {
              self.isLoading = false
              uni.hideLoading()
              console.log('登录失败！' + res.errMsg)
            }
          }
        })
      },
      accept() {
        const self = this
        self.checkInProject()
      },
      getPhone (e) {
        const self = this
        uni.request({
          url: '/sys/getPhoneNumber',
          method: 'POST',
          data: {
            code: e.detail.code
          },
          success(result) {
            if (result.data.success && result.data.data?.phoneNumber) {
              self.savePhoneNumber(result.data.data?.phoneNumber)
            }
          }
        })
      },
      savePhoneNumber(phoneNumber) {
        const self = this
        uni.request({
          url: '/user/modify',
          method: 'POST',
          data: {
            phone: phoneNumber
          },
          success(result) {
            if (result.data.success) {
              self.checkInProject()
            }
          }
        })
      },
      checkInProject() {
        const self = this
        uni.request({
          url: '/project_members/check',
          method: 'POST',
          data: {
            xm_id: self.projectId,
            user_id: self.userId
          },
          success(result) {
            if (result.data.data === 0) {
              self.joinProject()
            } else {
              uni.hideLoading()
              self.toNext()
            }
          }
        })
      },
      joinProject() {
        const self = this
        uni.request({
          url: '/project_members/add',
          method: 'POST',
          data: {
            xm_id: self.projectId,
            user_id: self.userId,
            permission: self.permissions,
            state: 0,
            show_on_wall: 0,
            key: self.shareKey
          },
          success(result) {
            if (result.data.success) {
              self.toNext()
            }
          },
          finally() {
            uni.hideLoading()
          }
        })
      },
      toNext() {
        const self = this
        if (!self.hasUserName) {
          self.toUserInfoSetting()
        } else {
          self.toIndex()
        }
      },
      toIndex() {
        const self = this
        uni.navigateTo({
          url: '/pages/entrance/index/index'
        })
      },
      toUserInfoSetting() {
        const self = this
        uni.navigateTo({
          url: '/pages/me/edit-info/edit-info?toIndex=1'
        })
      },
      reject() {
        const self = this
        uni.reLaunch({
          url: '/pages/entrance/login/login'
        })
      }
    }
  }
</script>

<style lang="scss" scoped>
.share-box {
  height: 100vh;
  background-color: $white;
  .error-msg {
    padding: 25vh 40rpx 0;
    text-align: center;
    font-size: 48rpx;
  }
}
.info-box {
  padding: 160rpx 115rpx;
  text-align: center;
}
.user-box {
}
.user-icon {
  margin: auto;
  width: 100rpx;
  height: 100rpx;
  border-radius: 50%;
  font-size: 100rpx;
  color: $primary;
}
.user-info {
  margin-top: 20rpx;
  font-size: $font-size-2;
  color: $text-base;
}
.project-box {
  margin-top: 20rpx;
}
.project-name {
  font-weight: bold;
  font-size: $font-size-4;
}
.btn-box {
  margin-top: 80rpx;
}
.btn-item {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 100%;
  height: 90rpx;
  border-radius: 10rpx;
  font-size: $font-size-4;
  border: 0;
  &.accept {
    background-color: $primary;
    color: $white;
  }
  &.reject {
    margin-top: 30rpx;
    background-color: $background-info;
    color: $text-secondary;
  }
}
</style>
